package org.openlab.dao.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.openlab.dao.BaseDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

@Repository
@RequiredArgsConstructor
public abstract class BaseDaoImpl<T, PK extends Serializable> implements BaseDao<T, PK> {
	
	protected final Log log = LogFactory.getLog(getClass());
	
	@Autowired
	@Getter(AccessLevel.PROTECTED)
	protected SessionFactory sessionFactory;
	
	private final Class<T> persistantClass;
	
	protected Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	@SuppressWarnings("unchecked")
	public List<T> getAll() {
		return new ArrayList<T>(this.getCurrentSession().createCriteria(persistantClass).list());
	}
	
	public List<T> getAllDistinct() {
		Collection<T> result = Sets.newLinkedHashSet(this.getAll());
		return new ArrayList<T>(result);
	}
	
	@SuppressWarnings("unchecked")
	public T get(PK id) {
		return (T) this.getCurrentSession().get(persistantClass, id);
	}
	
	public boolean exists(PK id) {
		return this.get(id) != null;
	}
	
	public void remove(PK id) {
		this.getCurrentSession().delete(this.get(id));
	}
	
	public T save(T entity) {
		this.getCurrentSession().saveOrUpdate(entity);
		return entity;
	}
}

